﻿using System.Linq;
using MailMerge.Infrastructure;

namespace MailMerge
{
	public class ArrearsBuilder : DocumentBuilder<ArrearsModel>
	{
		public ArrearsBuilder(ArrearsModel model) : base(model) {}
		public override string TemplateFileName
		{
			get
			{
				return 
					string.IsNullOrWhiteSpace(base.TemplateFileName) 
					? "Documents/ArrearsLetter.docx" 
					: base.TemplateFileName;
			}
			set
			{
				base.TemplateFileName = value;
			}
		}
		public override void Build(string outputPath)
		{
			base.Build(outputPath);
			BindModel(Model);
		}

		private void BindModel(ArrearsModel model)
		{
			var allContent = Document.GetContentControls();
			var modelProperties = typeof (ArrearsModel).GetProperties();
			foreach (var modelProperty in modelProperties)
			{
				var value = modelProperty.GetValue(model, null);
				var name = modelProperty.Name;
				var matchingContentControls = allContent.Where(cc => cc.Tag == name);
					
				foreach (var contentControl in matchingContentControls)
					contentControl.OverwriteText((string) value);
			}
		}
	}
}
